<template>
  
  <div class="canvas_box">
<!--      这个button是用来进行测试用的-->
    {{defailtlink}}
    <el-button @click="test" style="display: none"></el-button>
    
    <input  id="backgroud" @change="uploadBackgroud($event)" type="file" style="display: none" />
    <input id="mask" @change="uploadmask($event)" type="file" style="display: none" />
    <div><canvas v-if="width!==''" id='canvas' :width='width' :height='height' style="border:2px solid #cf9236;"></canvas></div>
    <div class="canvas_tool_right">
      
      <el-tooltip class="item" effect="dark" content="重置" placement="left">
        <el-button class="mt-15" type="danger"  icon="el-icon-s-home" circle @click="correct" ></el-button>
      </el-tooltip>
  
  
      <el-tooltip class="item" effect="dark" content="编辑对象" placement="left">
        <el-button class="mt-15" type="primary"  icon="el-icon-full-screen" circle @click="objedit" ></el-button>
      </el-tooltip>
  
  
      
  
      <el-tooltip class="item" effect="dark" content="打开底层图片" placement="left">
        <el-button class="mt-15" type="primary" icon="el-icon-picture-outline" circle @click="OpenImage"></el-button>
      </el-tooltip>
  
      <el-tooltip class="item" effect="dark" content="打开涂层" placement="left">
        <el-button class="mt-15" type="danger"  icon="el-icon-picture" circle @click="addmask"></el-button>
      </el-tooltip>
  
      <el-tooltip class="item" effect="dark" content="移动" placement="left">
        <el-button class="mt-15" type="primary" :plain="!moveable" icon="el-icon-rank" circle @click="changemove" ></el-button>
      </el-tooltip>
      
      <el-tooltip class="item" effect="dark" content="删除对象" placement="left">
        <el-button class="mt-15" type = "danger" icon = "el-icon-delete" circle @click="deletobj"></el-button>
      </el-tooltip>
      
  
      <el-tooltip class="item" effect="dark" content="编辑" placement="left">
        
        
        
        <el-dropdown trigger="click" @command="freeDrawn"  circle>
          <el-button class="mt-15" type="success" :plain="!drawable" icon="el-icon-edit" circle></el-button>
          <el-dropdown-menu slot="dropdown" >
            <el-dropdown-item plain command=1>画笔</el-dropdown-item>
            <el-dropdown-item plain command=2>方块</el-dropdown-item>
            <el-dropdown-item plain command=3>圆</el-dropdown-item>
            <el-dropdown-item plain command=4>三角</el-dropdown-item>
            <el-dropdown-item plain command=5>自定义</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-tooltip>
  
    </div>
    <div class="canvas_tool_left">
  
      <el-tooltip class="item" effect="dark" content="颜色选择-默认红色" placement="left">
        <el-color-picker class="mt-15" v-model="color" show-alpha :predefine="predefineColors" circle ></el-color-picker>
      </el-tooltip>
      
      <el-tooltip class="item" effect="dark" content="另存为" placement="left">
        <el-button class="mt-15" type="success" icon="el-icon-check" circle @click="save"></el-button>
      </el-tooltip>
      
      
      <el-tooltip class="item" effect="dark" content="设置" placement="left">
        <el-button class="mt-15" type="primary"  icon="el-icon-setting" circle @click="drawer = true"></el-button>
      </el-tooltip>
  
      <el-tooltip class="item" effect="dark" content="撤销" placement="left">
        <el-button class="mt-15" type="primary" icon="el-icon-refresh-left" circle @click="undo"></el-button>
      </el-tooltip>
  
      <el-tooltip class="item" effect="dark" content="返回" placement="left">
        <el-button class="mt-15" type="danger" icon="el-icon-refresh-right" circle @click="redo"></el-button>
      </el-tooltip>
      
    </div>
    <el-drawer title="Setting" :visible.sync="drawer"  >
      <div class="block" center>
        <el-slider v-model="pencliSize"
                   :format-tooltip="formatTooltip"
                   >
<!--                   height="200px"-->
<!--                   vertical-->
<!--                   >-->
        
        </el-slider>
        <p> 画笔大小尺寸</p>
        
        <el-slider v-model="opacity"
                   :format-tooltip="formatopacity"
        >
  
        </el-slider>
        <p> 掩图透明度</p>
      </div>
    </el-drawer>

  </div>
  

</template>

<script>
import { fabric } from 'fabric';
import {request} from './network/index';

export default {
  name: 'Fabric',
  props: {
},
  created(){
    console.log('开始创建')
    request({
      url: 'app/show/'
    }).then(res => {
      this.defailtlink = res.data
      this.backgroudurl = res.data['imgs_path'] + '.jpg'
      this.maskurl = res.data['imgs_path'] + '.png'
      console.log(this.maskurl);
      console.log(this.backgroudurl);
      
      
    }).catch(err => {
      console.log(err)
    })

  },

  data () {
    return {
      canvas: '',
      
      img:'',
      rect:null,
      
      width: '1220',
      height: '680',
      predefineColors:[
        '#ff0000',//rgb(255,0,0)
        '#0000FF',//rgb(0,0,255)
        '#00FF00',//rgb(0,255,0)
        '#FFFF00',//rgb(255,255,0)
        '#FF00FF',//rgb(255,0,255)
        '#00FFFF',//rgb(0,255,255)
      ],
      
      color: '#ff0000',
      
    
      pencliSize: 20,
      opacity: 20,
      
      
      activeIndex: null,
      isSelect: false,
      fileStearm: '',
      backgroudurl: '',
      maskurl:'',
      
      panning: false,
      moveable: false,
      
      backimg:'',

      
      tool_name:'pencil',
      drawable:false,
      doDrawing:false,
      lastDrawObject:null,
      drawingObject:null,

      fabricHistoryJson:[],
      mods:0,
      ishistory:false,


      moveCount:1,
      mouseFrom:{},
      mouseTo:{},
      mouseArray_X:[],
      mouseArray_Y:[],
      
      LineArray:[],//自定义的线段集合
      objectSets:[],//自定义的最终显示在画图对象的集合
      
      zoomPoint:new fabric.Point(0,0),//初始时缩放原点的位置设为（0,0），这是页面的左上顶点
      lastzoomPoint:{x:0,y:0},//，前一次缩放原点在画布上的同样为(0,0)
      lastmousePoint:{x:0,y:0},//进行缩放，需要对此刻缩放位置进行保存，来计算出缩放原点，此刻初始时设为0,0
      lastzoom:1,//表示为上一次的缩放倍数，此刻设为1
      zoom:1,//
      
      relativeMouseX:0,//表示相对的鼠标位移，用来记录画布的绝对移动距离
      tempmouseX:0,//
      tempmouseY:0,
      relativeMouseY:0,//表示相对的鼠标位移，用来记录画布的绝对移动距离

      drawer:false,

      defailtlink: 'none',
    
 
    }
  },
  watch:{
    color(newvalue){
      this.canvas.freeDrawingBrush.color = newvalue
    },

    opacity(newvalue){
      console.log(this.canvas.getObjects(),'image.opacity',this.canvas.getObjects()[0].opacity)
      this.canvas.getObjects()[0].set({
        'opacity':newvalue / 100
      })
      
      this.canvas.renderAll()
    }
  },

  mounted () {
    // 声明画布
    this.initCanvas()
    this.InitNews()
  },
  methods: {
    
    
    
    //初始化获得canvas对象
    initCanvas(){
        // 1. 实例化canvas 画布
        this.canvas = new fabric.Canvas("canvas",{
          isDrawingMode: false,
          selectable: false,
          selection: false,
          devicePixelRatio:true,
          defaultCursor:'default',
          hoverCursor:'default',
          moveCursor: 'default',
          //Retina 高清屏 屏幕支持
        });
      
      
      this.canvas.on({
       'object:added': (e) => {
        if(e.target.type == 'image'){
          this.img = e.target
          this.history = false
          e.target.set({
            'selectable':false,
          })
          // console.log(e.target.opacity)
        }else {
          console.log('sss')
        }

      },
        "mouse:down": (e) => {
         console.log(this.canvas.upperCanvasEl.style.cursor)
        }
        })

      },
// #####################操作历史记录###############################

    updateModifyHistory(saveHistory){
      if(saveHistory){
        this.fabricHistoryJson.push(JSON.stringify(this.canvas))
      }
    },
    undo() {
      if(this.fabricHistoryJson.length == 0){
        this.errortips(3)
        return;
      }
      let state = this.fabricHistoryJson
      console.log('undo',state.length)
      // this.canvas.on('object:added',function (e) {
      //   if(e.target.type == 'image'){
      //     e.target.set('selectable',false)
      //   }else {
      //     console.log('sss')
      //   }
      //
      // })
      if(this.mods < state.length) {
        this.canvas.clear().renderAll()
        this.canvas.loadFromJSON(state[state.length - 1 - this.mods - 1])
        this.ishistory = true
        this.canvas.renderAll()
        
        this.mods += 1;
      }
    },
    redo() {
      if(this.mods == this.fabricHistoryJson.length){
        this.errortips(4)
        return;
      }
      let state = this.fabricHistoryJson
      if (this.mods > 0) {
        this.canvas.clear().renderAll();
        this.ishistory=true
        this.canvas.loadFromJSON(state[state.length - 1 - this.mods + 1]);
        this.canvas.renderAll();
        this.mods -= 1;
      }
    },
    
    
//####################### end 历史记录功能##########################
    
// ###############测试使用的函数###############
    test(){
      let item = new fabric.Rect({
        left:0,
        top:0,
        fill:'green',
        width:50,
        height:50
      })
      this.canvas.add(item)
      this.canvas.renderAll()
      
     

    },

    
//###########end 测试结束##########################
    
    
    formatTooltip(val) {
      return val / 20;
    },
    formatopacity(val){
      return val / 100
    },
    
    
//############## Setting #############################
    


//###############end Setting ###########################
    
//########################### 画图功能 ########################################################

    freeDrawn(command){
      if(this.backimg == ''){
        this.errortips(1)  // 表示还未加载底层图片
        return;
      }
      if(this.img == ''){
        this.errortips(2) //表示还未加载图层
        return;
      }
      this.drawable = true
      this.moveable = false
      this.canvas_off(this.canvas)
      this.zoom_move_canvas(this.canvas,this.moveable)

      this.de_activeObjects(false)//设定所有对象为不可选中
      this.canvas.set({
        hoverCursor:'crosshair'
      })
      
      if(this.drawable){
        
        if(command == 1){
          this.tool_name = 'pencil'
        } else if(command == 2){
          this.tool_name = 'rect'
        } else if(command == 3){
          this.tool_name = 'circle'
        } else if(command == 4){
          this.tool_name = 'triangle'
        } else if(command == 5){
          this.tool_name = 'define'
        }
        
        
        
        this.canvas.on({
          'mouse:down': (o)=> {
            this.mouseFrom.x = this.lastzoomPoint.x + (o.pointer.x - this.zoomPoint.x - this.relativeMouseX) / this.canvas.getZoom();
            this.mouseFrom.y = this.lastzoomPoint.y + (o.pointer.y - this.zoomPoint.y - this.relativeMouseY) / this.canvas.getZoom();
            
            this.doDrawing = true;
            
            
          },
          'mouse:up':(o)=>{
            this.mouseTo.x = this.lastzoomPoint.x + (o.pointer.x - this.zoomPoint.x - this.relativeMouseX) / this.canvas.getZoom();
            this.mouseTo.y = this.lastzoomPoint.y + (o.pointer.y - this.zoomPoint.y - this.relativeMouseY) / this.canvas.getZoom();
            this.doDrawing = false
            this.drawingObject = false
            
            if(command == 5){
              this.mouseArray_X.push(this.mouseTo.x);
              this.mouseArray_Y.push(this.mouseTo.y);
              this.ligature(this.canvas);
            }
            
            
            this.updateModifyHistory(true)
            
          },
          'mouse:dblclick':()=>{
            console.log('db_1')
            this.define_graph(this.canvas);
            this.mouseArray_X = [];
            this.mouseArray_Y = [];
          },
          'mouse:move':(o)=> {
            if (!this.doDrawing){
              return
            }
            this.moveCount++;
            this.mouseTo.x = this.lastzoomPoint.x + (o.pointer.x - this.zoomPoint.x - this.relativeMouseX) / this.canvas.getZoom();
            this.mouseTo.y = this.lastzoomPoint.y + (o.pointer.y - this.zoomPoint.y - this.relativeMouseY) / this.canvas.getZoom();
            
            this.drawing(this.canvas);
            
          },
        })
        
        
      }else {
        this.tool_name = 'pencil'
      }
      
      
    },
    ligature(canvas){
      const length = this.mouseArray_X.length
      if (length > 1){
        
        this.LineArray.push(new fabric.Line(
          [this.mouseArray_X[length-2],
            this.mouseArray_Y[length-2],
            this.mouseArray_X[length-1],
            this.mouseArray_Y[length-1]],
          {
            stroke: '#ff00ff',
            strokeWidth: 0.4,
            selectable:false,
            selection:false
          }));
        canvas.add(this.LineArray[this.LineArray.length - 1]);
      }
    },
    
    define_graph(canvas){
      const len = this.mouseArray_Y.length;
      let T = "M " + this.mouseArray_X[0]+" "+this.mouseArray_Y[0]+" ";

      for (let i=1;i<len;i++){
        T +=" L " + this.mouseArray_X[i]+" "+this.mouseArray_Y[i]+" ";
      }
      T +=" z";
      let obj  = new fabric.Path(T,{
        fill:this.color
      })
      obj.set({
        selectable: false,//设定可以被选中
      })
      canvas.add(obj);
      this.objectSets.push(obj)
      
      
      for (let i=0;i<len-1;i++){
        canvas.remove(this.LineArray[i])
      }
      
      canvas.renderAll();
    },
    
    drawing(canvas){
      if (this.drawingObject){
        canvas.remove(this.drawingObject)
        this.objectSets.pop()
      }
      
      let drawObj = null
      switch (this.tool_name) {
        case "pencil":
          canvas.freeDrawingCursor = "default"
          canvas.freeDrawingBrush.color = this.color
          canvas.freeDrawingBrush.width = this.pencliSize / 20 //滑块值除以20后的值赋给
          canvas.isDrawingMode = true
          
          break
        
        case "rect":
          let path =  "M " +
            this.mouseFrom.x +
            " " +
            this.mouseFrom.y +
            " L " +
            this.mouseTo.x +
            " " +
            this.mouseFrom.y +
            " L " +
            this.mouseTo.x +
            " " +
            this.mouseTo.y +
            " L " +
            this.mouseFrom.x +
            " " +
            this.mouseTo.y +
            " L " +
            this.mouseFrom.x +
            " " +
            this.mouseFrom.y +
            " z";
          drawObj = new fabric.Path(path,{
            fill:this.color
          })

          break
        case "circle":
          let radius = Math.sqrt((this.mouseTo.x - this.mouseFrom.x) * (this.mouseTo.x - this.mouseFrom.x) + (this.mouseTo.y - this.mouseFrom.y) * (this.mouseTo.y - this.mouseFrom.y));
          drawObj = new fabric.Circle({
            left: this.mouseFrom.x - radius,
            top: this.mouseFrom.y - radius,
            fill: this.color,
            radius: radius,
          });
          break
        
        case "triangle":
          let height = this.mouseTo.y - this.mouseFrom.y;
          drawObj = new fabric.Triangle({
            top: this.mouseFrom.y,
            left: this.mouseFrom.x,
            width: Math.sqrt(Math.pow(height, 2) + Math.pow(height / 2.0, 2)),
            height: height,
            fill: this.color
          });
          
          break
        case "define":

          break
          
          
        default:
          break;
      }
      
      if(drawObj){
        drawObj.set({
          selectable: false,//设定可以被选中
        })
        canvas.add(drawObj)
        this.drawingObject = drawObj
        this.objectSets.push(drawObj)
      

      }
      
    },

    


//#######################end  画图##############################################
    
    //解除canvas的绑定、可移动性
    canvas_off(canvas){
      canvas.off("mouse:down");
      canvas.off("mouse:up");
      canvas.off("mouse:wheel");
      canvas.off("mouse:move");
      canvas.off("mouse:dblclick")
      canvas.isDrawingMode = false
    },

    

//###################移动缩放画布##########################################
    //移动画布和缩放功能
    changemove(){
      this.canvas.set({
        hoverCursor:'move'
      })
      
      if(this.backimg == ''){
        this.errortips(1)  // 表示还未加载底层图片
        return;
      }
      if(this.img == ''){
        this.errortips(2) //表示还未加载图层
        return;
      }
     
      this.moveable = true
      this.drawable = false
      this.canvas_off(this.canvas)
      this.zoom_move_canvas(this.canvas,this.moveable)

      this.de_activeObjects(false)//设定所有对象为不可选中
      
      
      
    },
    
   //对画布进行缩放和移动
    zoom_move_canvas(canvas,moveable) {
      
      if (moveable) {
        console.log('onmove:', this.moveable, 'now_draw:', this.drawable)

        canvas.on({
          "mouse:down": (e) => {
            
            this.panning = true;
            canvas.selection = false;
            //

            
          },

          "mouse:up": (e) => {
            this.panning = false;
            canvas.selection = true;
          },


          "mouse:move": (e) => {
         
            // console.log('move:',this.panning)
            if (this.panning && e && e.e) {
              let delta = new fabric.Point(e.e.movementX, e.e.movementY);
              
              // console.log('delta:', delta, 'movemenntX,Y', e.e.movementX, e.e.movementY);
              canvas.relativePan(delta);
              this.relativeMouseX += e.e.movementX;
              this.relativeMouseY += e.e.movementY;
              // console.log('now_obj',this.canvas.getActiveObject().selectable)
              
              


            }
            
            // console.log('rect_x_y:', this.rect.top, this.rect.left)
          },
          "mouse:wheel": (e) => {
            this.zoom = (event.deltaY > 0 ? -0.1 : 0.1) + canvas.getZoom();
            this.zoom = Math.max(0.1, this.zoom); //最小为原来的1/10
            this.zoom = Math.min(3, this.zoom); //最大是原来的3倍
            // console.log('pageX pageY',event.pageX,event.pageY)
            console.log("lastPointX_Y:",this.lastzoomPoint.x,this.lastzoomPoint.y);
            this.zoomPoint = new fabric.Point(e.pointer.x,e.pointer.y);//获得此刻缩放原点在页面上的原点
            

            console.log('zoomPoint_x_y:',this.zoomPoint.x,this.zoomPoint.y,'zoom',this.zoom)
            canvas.zoomToPoint(this.zoomPoint, this.zoom)
            console.log('getzoom:',canvas.getZoom())
            
            
            
            //
            // console.log('rect1:',rect1.top,rect1.left,'rect2:',rect2.top,rect2.left)
            // // this.relativeMouseX =  event.pageX - mouseX
            // // this.relativeMouseY =  event.pageY - mouseY
            // console.log('rel_X_Y:',this.relativeMouseX ,this.relativeMouseY)


            this.lastzoomPoint.x = this.lastzoomPoint.x + (this.zoomPoint.x - this.lastmousePoint.x - this.relativeMouseX) / this.lastzoom
            this.lastzoomPoint.y = this.lastzoomPoint.y + (this.zoomPoint.y - this.lastmousePoint.y - this.relativeMouseY) / this.lastzoom

            this.lastmousePoint.x = this.zoomPoint.x
            this.lastmousePoint.y = this.zoomPoint.y
            this.lastzoom = this.zoom
            

            this.tempmouseX = this.relativeMouseX
            this.tempmouseY = this.relativeMouseY
            //
            // this.zoomPoint.x = this.zoomPoint.x - this.tempmouseX
            // this.zoomPoint.y = this.zoomPoint.y - this.tempmouseY
            //
            this.relativeMouseX = 0
            this.relativeMouseY = 0
            
            
            
            
            
            
          },
          
        })
      }
    },
//############ end 移动和缩放画布########################################

//###########  删除对象 ################################
  deletobj(){
    
    this.objedit()
    
    this.canvas.on({
      "mouse:down":(o)=>{
        
        let obj = this.canvas.getActiveObject()
        this.updateModifyHistory(true)
        this.canvas.remove(obj)
      },
    })
    
    
  },
    ///  对绘画的对象进行激活或灭活
  de_activeObjects(isActive){
      for(let i =0;i<this.objectSets.length;i++){
        this.objectSets[i].set({
          selectable:isActive,
        })
      }
    },

//############结束删除对象 ###########################

//###############  编辑对象 ############################

    objedit(){
      this.drawable = false
      this.moveable = false

      this.canvas_off(this.canvas)
      this.de_activeObjects(true)
    },
//#################end 编辑对象############################
    
//##################### 重置一切 #############################
  correct () {
      if(this.backimg == ''){
        this.errortips(1)  // 表示还未加载底层图片
        return;
      }
      if(this.img == ''){
        this.errortips(2) //表示还未加载图层
        return;
      }
      
      let delta = new fabric.Point(0,0);
      this.canvas.absolutePan(delta);
      
      let zoom = 1
      this.canvas.zoomToPoint(delta, zoom);
      
      this.relativeMouseY = 0;
      this.relativeMouseX = 0;
      this.zoomPoint = new fabric.Point(0,0);
      this.fabricHistoryJson = [];


      this.lastzoom = 1;

      this.moveCount = 1;
      this.mouseFrom = {};
      this.mouseTo = {};
      this.mouseArray_X=[];
      this.mouseArray_Y=[];
      this.LineArray=[];
      
      this.lastzoomPoint={x:0,y:0};//，前一次缩放原点在画布上的同样为(0,0)
      this.lastmousePoint={x:0,y:0};//进行缩放，需要对此刻缩放位置进行保存，来计算出缩放原点，此刻初始时设为0,0
      this.zoom=1;
      
      this.de_activeObjects(false)//设定所有对象为不可选中
      
    },
    
//#####################保存图片##########################################
    save () {
      if(this.backimg == ''){
        this.errortips(1)
        return;
      }
      if(this.img == ''){
        this.errortips(2)
        return;
      }
      
      
      this.canvas.width = this.backimg.width
      this.canvas.height= this.backimg.height
      const url = this.canvas.toDataURL()
      var blob = this.dataURLtoBlob(url)
      var file = this.blobToFile(blob, '截图.png')
      // console.log(url)
      // console.log(file)
      this.fileStearm = file
      // 组装a标签
      let elink = document.createElement('a')
      // 设置下载文件名
      elink.download = '截图.png'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    },
    // 将base64转换为blob
    dataURLtoBlob: function (dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {type: mime})
    },
    // 将blob转换为file
    blobToFile: function (theBlob, fileName) {
      theBlob.lastModifiedDate = new Date()
      theBlob.name = fileName
      return theBlob
    },
//#########################end 保存图片#############################################
    //激活对应的input元素
    activeinput(id_name){
      let dom = document.getElementById(id_name)
      dom.click()
    },
    
//############################# mask加载####################################################
    //#1.通过button激活input的文件选择
    addmask(){
      if (this.maskurl == '') {
        this.activeinput('mask')
      }else{
        console.log('mask auto load');
        this.loadmask()
      }
      // if(this.backimg != '' ){
      //   this.activeinput('mask')
      // }else{
      //   this.errortips(1)
      // }
      
    },
    //#2 将图片转换成base64的形式
    uploadmask(el){
      if (!el.target.files[0].size) return // 如果文件大小为0，则返回
      if (el.target.files[0].type.indexOf('image') === -1) { // 如果不是图片格式
        console.log('请选择图片文件')
      } else {
        console.log(el.target.files[0])
        const that = this
        const reader = new FileReader() // 创建读取文件对象
        reader.readAsDataURL(el.target.files[0]) // 发起异步请求，读取文件
        reader.onload = function () { // 文件读取完成后
          // 读取完成后，将结果赋值给img的src
          
          that.maskurl = this.result
          that.loadmask()
        }
        
      }
      console.log(this.canvas.upperCanvasEl.style.cursor)
    },
    //#3.开始加载mask
    loadmask(){

        fabric.Image.fromURL(this.maskurl,(img)=>{
          img.set({
            scaleX: this.canvas.width / img.width,
            scaleY: this.canvas.height / img.height,
            opacity:this.opacity / 100,
            hasControls:false,
            borderColor:'orange',
            selectable:false,
            selection:false,
            preserveObjectStacking:true,
            
          });
          this.img = img
          this.canvas.add(img)
          this.canvas.renderAll()
          
        })

      
      
    },
//#########################end mask加载#########################################
//     change_canvasSize(height,width){
//       this.canvas.upperCanvasEl.width = width
//       this.canvas.upperCanvasEl.height= height
//
//       this.canvas.lowerCanvasEl.width = width
//       this.canvas.lowerCanvasEl.height= height
//
//
//       this.canvas.upperCanvasEl.style["width"] = width+"px"
//       this.canvas.upperCanvasEl.style['height'] = height+"px"
//
//       this.canvas.lowerCanvasEl.style['width'] = width + 'px'
//       this.canvas.lowerCanvasEl.style['height'] = height + 'px'
//
//
//
//
//     },


//#################  backgroud image 加载###################################
    // #1.通过button激活input的文件选择
    OpenImage: function () {
      if (this.backgroudurl != '') {
        this.loadbackimg()
      }else{
        this.activeinput('backgroud')
      }

      
    },
    //#2.将图片转换为base64
    uploadBackgroud (el) {
      if (!el.target.files[0].size) return // 如果文件大小为0，则返回
      if (el.target.files[0].type.indexOf('image') === -1) { // 如果不是图片格式
        // this.$dialog.toast({ mes: '请选择图片文件' });
        console.log('请选择图片文件')
      } else {
        
        const that = this
        const reader = new FileReader() // 创建读取文件对象
        console.log(el.target.files[0]);
        reader.readAsDataURL(el.target.files[0]) // 发起异步请求，读取文件
        reader.onload = function () { // 文件读取完成后
          // 读取完成后，将结果赋值给img的src
          that.backgroudurl = this.result
          that.canvas.clear()
          that.correct()
          that.loadbackimg()
        }
      }
    },
    //#3. 加载背景图片功能
    loadbackimg () {
      this.$nextTick(() => {

        fabric.Image.fromURL(this.backgroudurl,(img)=>{


          console.log('img:',img.height,img.width)
          if(img.height > this.height && img.width>this.width)
          {
            this.canvas.width = img.width
            this.canvas.height= img.height
          }else{
            this.canvas.width = this.width
            this.canvas.height= this.height
          }
          this.backimg = img
          console.log('canvas:',this.canvas.width,this.canvas.height)
          this.canvas.setBackgroundImage(img,this.canvas.renderAll.bind(this.canvas),{
            // scaleX:this.canvas.width / img.width,
            // scaleY:this.canvas.height / img.height
          });
          

        })
        
      })
      
    },

//##############################end 加载背景图########################

//################################  初始消息 ######################################
    InitNews(){
      this.$alert('你需要先加载底层图片，然后加载图层之后才能进行编辑。','图片编辑的功能介绍',{
        confirmButtonText:'确实',
        callback:action => {
          this.$message({
            type:'info',
            message: '欢迎使用本网站'
          });
        }
      });
    },
//#################################  end 初始消息##################################

//#################################  错误操作提示信息 ########################################
    errortips(n){
      let tips = ['还未加载完成，请稍等。。。','你还未加载底层图片,不能执行该操作','你还未加载图层，不能执行该操作','此时还未操作不能进行撤销','此时已经达到最大不能返回']
      this.$notify({
        title:'提示',
        message:tips[n],
        position:'bottom-left'
      });
    },

//################################# end 错误操作提示信息 ####################################
  }
}
</script>

<style scoped lang="scss">
  .canvas_box{
    width:100%;
    height:100%;
    padding-left: 6em;
    position: center;


    .canvas_tool_right{
      width:80px;
      height:100%;
      box-sizing:border-box;
      padding:20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      box-shadow: 0 0 10px #edef64;
      position:fixed;
      right:0;
      top:0;
      background:cadetblue;
    }
    .canvas_tool_left{
      width:80px;
      height:100%;
      box-sizing:border-box;
      padding:20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      box-shadow: 0 0 10px #edef64;
      position:fixed;
      left:0;
      top:0;
      background:greenyellow;
    }
    /*.canvas_container{*/
    /*  .canvas_wrapper{*/
    
    /*  }*/
    /*}*/
    .el-button+.el-button{
      margin-left: 0 !important;
    }
    .mt-15{
      margin-top:15px;
    }
  }
</style>


